package modelo;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;

import dao.PerfilDao;
import excepciones.DaoException;

import beans.SeleccionPerfilBean;

@FacesConverter( value="perfilConverter" )
public class PerfilConverter implements Converter{

	public String getAsString(FacesContext context, UIComponent component, Object value) {
        // Convert the Foo object to its unique String representation.
        //return ((Perfil) value).getNombre();
        return (value instanceof Perfil) ? ((Perfil) value).getNombre() : null;

    }

	@Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
		
		PerfilDao perfilDao = new PerfilDao();
		Perfil perfil = null;
		try {
			perfil = (Perfil) perfilDao.encontrarPorNombre(value);
			perfilDao.closeEntityManager();
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//System.out.println(value);
        return perfil;
		/*
		if (value == null) {
            return null;
        }

        SeleccionPerfilBean data = context.getApplication().evaluateExpressionGet(context, "#{data}", SeleccionPerfilBean.class);

        for (SelectItem perfil : data.getPerfiles()) {
            if (perfil.getValue().equals(value)) {
                return perfil;
            }
        }

        throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to Perfil", value)));
        
    }*/
	}

}
